import { defineStore } from 'pinia'
import { ref } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'

export const useRemoteModeOptionsStore = defineStore('remoteModeOptions', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const posixTime = ref(Date.now())
  const isCustomized = ref(false)
  const result = ref(null)

  // 定时器引用
  let updateInterval = null

  // 动作
  function startUpdateTimer() {
    updateInterval = setInterval(() => {
      if (!isCustomized.value) {
        posixTime.value = Date.now()
      }
    }, 15)
  }

  function stopUpdateTimer() {
    if (updateInterval) {
      clearInterval(updateInterval)
      updateInterval = null
    }
  }

  function confirm() {
    result.value = parseInt(posixTime.value)
    hide()
  }

  function show() {
    return dialogQueue.show({
      onLoaded: () => {
        posixTime.value = Date.now()
        isCustomized.value = false
        result.value = null
        startUpdateTimer()
      },
      onHidden: () => {
        stopUpdateTimer()
        return result.value
      }
    })
  }

  function hide() {
    dialogQueue.hide(result.value)
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    posixTime,
    isCustomized,
    // 动作
    confirm,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 